package leetcode.code1092;

import leetcode.helper.H;
// 正面突破不好想啊....
public class Solution4 {
	public String shortestCommonSupersequence(String str1, String str2) {
		int m = str1.length(), n = str2.length();
		int[][] dp = new int[m + 1][n + 1];
		for (int i = 1; i <= m; i++) {
			for (int j = 1; j <= n; j++) {
				if (str1.charAt(i - 1) == str2.charAt(j - 1)) {
					dp[i][j] = dp[i - 1][j - 1] + 1;
				} else {
					dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
				}
			}
		}
		StringBuffer sb = new StringBuffer();
		int i = 1, j = 1;
		while (i <= m && j <= n) {
			if (str1.charAt(i - 1) == str2.charAt(j - 1) && (i + 1 > m || dp[i + 1][j] == dp[i][j])
					&& (j + 1 > n || dp[i][j + 1] == dp[i][j])) {
				sb.append(str1.charAt(i - 1));
				i++;
				j++;
			} else if (j + 1 <= m && dp[i][j] < dp[i][j + 1]) {
				sb.append(str2.charAt(j - 1));
				j++;
			} else {
				sb.append(str1.charAt(i - 1));
				i++;
			}
		}
		while (i <= m) {
			sb.append(str1.charAt(i - 1));
			i++;
		}
		while (j <= n) {
			sb.append(str2.charAt(j - 1));
			j++;
		}
		return sb.toString();
	}

	public static void main(String[] args) {
		Solution4 solution = new Solution4();
		solution.shortestCommonSupersequence("abac", "cab");

	}
}
